package com.hw.nio.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * 简易的http服务
 */
public class MyBootStrapTest {

    public void open(int port) throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup(8);

        bootstrap.group(bossGroup, workGroup);
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.childHandler(new ChannelInitializer<Channel>() {
            @Override
            protected void initChannel(Channel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("decode",new HttpRequestDecoder());
                pipeline.addLast("servlet",new SimpleChannelInboundHandler<Object>() {
                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                        System.out.println(msg.getClass().getName());
                        if(msg instanceof DefaultHttpRequest){

                            DefaultFullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK);
                            defaultFullHttpResponse.content().writeBytes("hello".getBytes(StandardCharsets.UTF_8));
                            ChannelFuture channelFuture = ctx.channel().writeAndFlush(defaultFullHttpResponse);
                            channelFuture.addListener(ChannelFutureListener.CLOSE);
//
                        }
                    }
                });
                pipeline.addLast("encode",new HttpResponseEncoder());
            }

            @Override
            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                super.exceptionCaught(ctx, cause);
                System.out.println(cause);
            }
        });
        ChannelFuture bind = bootstrap.bind(new InetSocketAddress(port));
        bind.addListener((ChannelFutureListener) future -> System.out.println("绑定端口"));
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        MyBootStrapTest myBootStrapTest = new MyBootStrapTest();
        myBootStrapTest.open(8082);
        System.in.read();
    }

}
